﻿using System.Data;
using JKF.BusinessLayer;
using JKF.BusinessLayer.BLL;
using JKF.Entities;
using JKF.Entities.Model;
using JKF.Substructure;
using SFWS.XHandler.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JKF.HandlerLayer.Sales
{
    public class Sales_ConsumeHandler : AHttpHandler
    {
        public override void ProcessRequest()
        {
            try
            {
                this.HandleRequest(Utils.GetActionName);
            }
            catch (Exception ex)
            {
                //将错误抛到客户端(以Json格式)
                Utils.ToClient(true, ex.Message);
                AppLogger.Log(ex.Message, ex);  //写日志
            }
        }

        #region Managers
        private static bllPRODUCT productManager = new bllPRODUCT();
        private static bllSALES_CONSUME salesConsume = new bllSALES_CONSUME();
        private static bllCUSTOMER customerMgr = new bllCUSTOMER();
        private static bllSYS_USER sysUserMgr = new bllSYS_USER();
        private static StringBuilder builder = new StringBuilder();
        #endregion

        #region Handlers

        /// <summary>
        /// 获得顾客购买记录Customer Info View
        /// </summary>
        [Exp2Client]
        public void GetConsumeByCustomer()
        {
            var customerKey = P("customerKey");
            if (!customerKey.IsGuidB()) throw new Exception("顾客编号格式不正确.");

            Response.Write(new ResponseInf
                {
                    Success = true,
                    Data = (from a in bllSALES_CONSUME.GetCustomerSalesConsume(customerKey, bllSYS_USER.CurrentUser.USER_KEY.ToString()).AsEnumerable()
                            select new
                                {
                                    CONSUME_KEY = a.Field<Guid>("CONSUME_KEY").ToString(),
                                    UNIQUE_CODE = a.Field<string>("UNIQUE_CODE"),
                                    CARD_NO = a.Field<string>("CUSTOMER_CARD_NO"),
                                    CUSTOMER_NAME = a.Field<string>("CUSTOMER_NAME"),
                                    MOBILE = a.Field<string>("CUSTOMER_MOBILE"),
                                    PHONE = a.Field<string>("CUSTOMER_PHONE"),
                                    PRODUCTNAME = a.Field<string>("PRODUCT_NAME"),
                                    MODEL = a.Field<string>("PRODUCT_MODEL"),
                                    WAY_CODE = a.Field<string>("WAY_CODE"),
                                    WAY_NAME = a.Field<string>("WAY_CODE") == "0" ? "购买" : (a.Field<string>("WAY_CODE") == "1" ? "更换" : "维修"),
                                    REGISTER_DATE = a.Field<DateTime?>("REGISTER_DATE").ToShortDateLineFormat(),
                                    MONEY = a.Field<decimal?>("MONEY").ToStringNoValue(),
                                    ADD_POINT = a.Field<int?>("ADD_POINT").ToStringNoValue(),
                                    STATUS = a.Field<string>("STATUS"),
                                    //EDITSHOW = a.Field<int>("isLock") > 0 ? "none" : "",
                                    OPERATER = a.Field<string>("OPERATOR"),
                                    MEMO = a.Field<string>("MEMO"),
                                    DATE_CREATE = a.Field<DateTime>("DATE_CREATE").ToShortDateLineFormat()
                                }).ToList()
                }.ToJson());
        }

        /// <summary>
        /// 配件更换维修记录列表数据
        /// </summary>
        public void GetSalesConsumeByPage()
        {
            var obj = new PagerList();
            var pageCount = 0;
            var rowCount = 0;
            var pageCurrent = 0;
            var pageSize = 20;
            var schPara = JsonSerializer.Deserialize<SearchOptions>(P("schOptions"));
            pageCurrent = int.TryParse(P("PageIndex"), out pageCurrent) ? pageCurrent : 0;
            pageSize = int.TryParse(P("PageSize"), out pageSize) ? pageSize : pageSize;
            var result = bllSALES_CONSUME.GetSalesContractPaging(schPara.REGISTER_DATESTART, schPara.REGISTER_DATEEND, schPara.STATE,
                schPara.SHOP_CODE, schPara.filterBy, schPara.filterOperater, schPara.fiterText, bllSYS_USER.CurrentUser.USER_KEY.ToString(), pageCurrent, pageSize, ref pageCount, ref rowCount);

            if (P("isExport") != "1")
            {
                obj.Entity = null == result ? null : (from a in result.AsEnumerable()
                                                      select new
                                                      {
                                                          CONSUME_KEY = a.Field<Guid>("CONSUME_KEY").ToString(),
                                                          UNIQUE_CODE = a.Field<string>("UNIQUE_CODE"),
                                                          CARD_NO = a.Field<string>("CUSTOMER_CARD_NO"),
                                                          CUSTOMER_NAME = a.Field<string>("CUSTOMER_NAME"),
                                                          MOBILE = a.Field<string>("CUSTOMER_MOBILE"),
                                                          PHONE = a.Field<string>("CUSTOMER_PHONE"),
                                                          PRODUCTNAME = a.Field<string>("PRODUCT_NAME"),
                                                          MODEL = a.Field<string>("PRODUCT_MODEL"),
                                                          WAY_CODE = a.Field<string>("WAY_CODE"),
                                                          WAY_NAME = a.Field<string>("WAY_CODE") == "0" ? "购买" : (a.Field<string>("WAY_CODE") == "1" ? "更换" : "维修"),
                                                          REGISTER_DATE = a.Field<DateTime?>("REGISTER_DATE").ToShortDateLineFormat(),
                                                          MONEY = a.Field<decimal?>("MONEY").ToStringNoValue(),
                                                          ADD_POINT = a.Field<int?>("ADD_POINT").ToStringNoValue(),
                                                          STATUS = a.Field<string>("STATUS"),
                                                          EDITSHOW = a.Field<int>("isLock") > 0 ? "none" : "",
                                                          OPERATER = a.Field<string>("OPERATOR"),
                                                          MEMO = a.Field<string>("MEMO"),
                                                          DATE_CREATE = a.Field<DateTime>("DATE_CREATE").ToShortDateLineFormat()
                                                      }).ToList();
                obj.RowCount = rowCount;
                obj.PageCount = pageCount;
                ResponseJsonObject = obj;
            }
            else
            {
                if (result == null) return;
                result.Columns.Add("WAY_NAME");
                foreach (DataRow row in result.Rows)
                {
                    row["WAY_NAME"] = row["WAY_CODE"].ToString() == "0"
                                          ? "购买"
                                          : (row["WAY_CODE"].ToString() == "1" ? "更换" : "维修");
                }
                //WAY_NAME = a.Field<string>("WAY_CODE") == "0" ? "购买" : (a.Field<string>("WAY_CODE") == "1" ? "更换" : "维修"),
                IDictionary<string, string> columns = new Dictionary<string, string>();
                columns.Add("CUSTOMER_CARD_NO", "顾客卡号");
                columns.Add("CUSTOMER_NAME", "姓名");
                columns.Add("CUSTOMER_MOBILE", "手机");
                columns.Add("UNIQUE_CODE", "销售单号");
                columns.Add("PRODUCT_NAME", "耗材/配件名称");
                columns.Add("PRODUCT_MODEL", "规格");
                columns.Add("WAY_NAME", "方式");
                columns.Add("DATE_CREATE", "登记日期");
                columns.Add("MONEY", "实收金额");
                columns.Add("ADD_POINT", "增加积分");
                columns.Add("MEMO", "备注");
                Excel.Export("配件.耗材维修记录", result, columns, Response, Excel.PageType.handler);
            }
        }

        /// <summary>
        /// 获得配件更换维修记录(By Customer)
        /// </summary>
        public void GetSalesConsumeByCustomer()
        {
            var customerKey = P("customerKey");
            if (!customerKey.IsGuidB()) throw new Exception("顾客编号格式不正确.");
            var obj = new PagerList();
            var pageCount = 0;
            var rowCount = 0;
            var pageCurrent = 0;
            var pageSize = 20;
            pageCurrent = int.TryParse(P("PageIndex"), out pageCurrent) ? pageCurrent : 0;
            pageSize = int.TryParse(P("PageSize"), out pageSize) ? pageSize : pageSize;

            var result = bllSALES_CONSUME.GetSalesConsumeForCustomerPaging(customerKey,
                                                                              bllSYS_USER.CurrentUser.USER_KEY.ToString(),
                                                                              pageCurrent, pageSize, ref pageCount,
                                                                              ref rowCount);

            obj.Entity = null == result ? null : (from a in result.AsEnumerable()
                                                  select new
                                                  {
                                                      CONSUME_KEY = a.Field<Guid>("CONSUME_KEY").ToString(),
                                                      UNIQUE_CODE = a.Field<string>("UNIQUE_CODE"),
                                                      CARD_NO = a.Field<string>("CUSTOMER_CARD_NO"),
                                                      CUSTOMER_NAME = a.Field<string>("CUSTOMER_NAME"),
                                                      MOBILE = a.Field<string>("CUSTOMER_MOBILE"),
                                                      PHONE = a.Field<string>("CUSTOMER_PHONE"),
                                                      PRODUCTNAME = a.Field<string>("PRODUCT_NAME"),
                                                      MODEL = a.Field<string>("PRODUCT_MODEL"),
                                                      WAY_CODE = a.Field<string>("WAY_CODE"),
                                                      WAY_NAME = a.Field<string>("WAY_CODE") == "0" ? "购买" : (a.Field<string>("WAY_CODE") == "1" ? "更换" : "维修"),
                                                      REGISTER_DATE = a.Field<DateTime?>("REGISTER_DATE").ToShortDateLineFormat(),
                                                      MONEY = a.Field<decimal?>("MONEY").ToStringNoValue(),
                                                      ADD_POINT = a.Field<int?>("ADD_POINT").ToStringNoValue(),
                                                      STATUS = a.Field<string>("STATUS"),
                                                      OPERATER = a.Field<string>("OPERATOR"),
                                                      MEMO = a.Field<string>("MEMO"),
                                                      DATE_CREATE = a.Field<DateTime>("DATE_CREATE").ToShortDateLineFormat()
                                                  }).ToList();
            obj.RowCount = rowCount;
            obj.PageCount = pageCount;
            ResponseJsonObject = obj;
        }

        /// <summary>
        /// 编辑
        /// </summary>
        [Exp2Client]
        public void EditSalesConsume()
        {
            var opSuccess = false;
            var bEdit = false;
            var salesConsumeJson = JsonSerializer.Deserialize<ConsumeJson>(P("salesConsume"));
            var consume = BuildConsume(salesConsumeJson);
            if (salesConsumeJson.CONSUME_KEY.IsGuidB())
            {//Edit
                bEdit = true;
                consume.CONSUME_KEY = salesConsumeJson.CONSUME_KEY.ToGuid();
                var serverModel = salesConsume.GetModel(consume.CONSUME_KEY);
                if (serverModel == null || (serverModel.STATUS == "9")) throw new Exception("待编辑项不存在.");
                //Do Update operation
                opSuccess = bllSALES_CONSUME.UpdateSalesConsume(consume);
                var customer = customerMgr.GetModel(consume.CUSTOMER_KEY);
                if (customer == null) throw new Exception("顾客不存在.");
                AppendLog(customer, serverModel, consume, LogType.Edit);
            }
            else
            {
                //Add new
                consume.CONSUME_KEY = DB.HR.GetNewGuid().ToGuid();
                consume.POINT_KEY = Guid.Empty;
                consume.USER_CREATE = bllSYS_USER.CurrentUser.USER_KEY;
                consume.STATUS = "1";
                consume.SHOP_CODE = bllSYS_USER.CurrentUser.SHOP_CODE;
                consume.UNIQUE_CODE = bllSALES_CONSUME.GetSalesConsumeUniqueCode(consume.SHOP_CODE);

                var outInfo = new STOCK_OUTinfo
                {
                    OUT_KEY = DB.HR.GetNewGuid().ToGuid(),
                    PRODUCT_KEY = consume.PRODUCT_KEY,
                    PRODUCT_NUMS = 1,
                    SHOP_CODE = consume.SHOP_CODE,
                    USER_CREATE = consume.USER_CREATE,
                    OUT_NO = string.Format("{0}{1}", consume.SHOP_CODE, DateTime.Now.ToString("yyyyMMddHHmmss")),
                    DATE_CREATE = DateTime.Now,
                    DATE_OUT = DateTime.Now,
                    DATE_UPDATE = DateTime.Now
                };

                var point = new POINT_LOGinfo()
                {
                    POINT_KEY = DB.HR.GetNewGuid().ToGuid(),
                    POINT_VALUE = consume.ADD_POINT.HasValue ? consume.ADD_POINT : 0,
                    CODE = "01",
                    WAY = "消费积分"
                };
                opSuccess = bllSALES_CONSUME.InsertSalesComsume(consume, point, outInfo);
                var customer = customerMgr.GetModel(consume.CUSTOMER_KEY);
                if (customer == null) throw new Exception("顾客不存在.");
                AppendLog(customer, consume, null, LogType.Add);
            }

            if (opSuccess)
            {
                //重新获取数据
                consume = salesConsume.GetModel(consume.CONSUME_KEY);
                var customer = customerMgr.GetModel(consume.CUSTOMER_KEY);
                var product = productManager.GetModel(consume.PRODUCT_KEY);
                var user = sysUserMgr.GetModel(consume.USER_CREATE);
                Response.Write(new ResponseInf
                {
                    Success = true,
                    Data = new
                    {
                        CONSUME_KEY = consume.CONSUME_KEY.ToString(),
                        UNIQUE_CODE = consume.UNIQUE_CODE,
                        CARD_NO = customer.CARD_NO,
                        CUSTOMER_NAME = customer.NAME,
                        MOBILE = customer.MOBILE,
                        PHONE = customer.PHONE,
                        PRODUCTNAME = product.NAME,
                        MODEL = product.MODEL,
                        WAY_CODE = consume.WAY_CODE,
                        WAY_NAME = consume.WAY_CODE == "0" ? "购买" : (consume.WAY_CODE == "1" ? "更换" : "维修"),
                        REGISTER_DATE = consume.REGISTER_DATE.ToShortDateLineFormat(),
                        MONEY = consume.MONEY.ToStringNoValue(),
                        ADD_POINT = consume.ADD_POINT.ToStringNoValue(),
                        STATUS = consume.STATUS == "1" ? "有效" : "无效",
                        OPERATER = user.REAL_NAME,
                        MEMO = consume.MEMO,
                        DATE_CREATE = consume.DATE_CREATE.ToShortDateLineFormat()
                    }
                }.ToJson());
                return;
            }
            throw new Exception(string.Format("{0}配件耗材维修记录失败.", bEdit ? "编辑" : "添加"));
        }

        /// <summary>
        /// 删除配件耗材
        /// </summary>
        [Exp2Client]
        public void RemoveConsume()
        {
            var consumeKey = P("consumeKey");
            if (!consumeKey.IsGuidB()) throw new Exception("配件/耗材维修登记记录编号格式不正确.");
            var dbModule = salesConsume.GetModel(consumeKey.ToGuid());
            if (dbModule == null) throw new Exception("待删除的配件/耗材维修登记记录不存在.");
            var rslt = bllSALES_CONSUME.RemoveSalesConsume(consumeKey);

            var customer = customerMgr.GetModel(dbModule.CUSTOMER_KEY);
            AppendLog(customer, dbModule, null, LogType.Delete);

            Response.Write(new ResponseInf
            {
                Success = (rslt == 1),
                Message = (rslt == 0) ? "删除配件/耗材维修登记记录失败." : ""
            }.ToJson());
        }
        #endregion

        #region clientObjBuilder
        /// <summary>
        /// Build sales consume info from client json string
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public SALES_CONSUMEinfo BuildConsume(ConsumeJson json)
        {
            int tmpInt;
            DateTime tmpDt;
            decimal tmpDeci;
            var consumeInfo = new SALES_CONSUMEinfo();
            if (!json.PRODUCT_KEY.IsGuidB()) throw new Exception("请选择配件/耗材.");
            if (!json.CUSTOMER_KEY.IsGuidB()) throw new Exception("请选择顾客.");
            consumeInfo.CUSTOMER_KEY = json.CUSTOMER_KEY.ToGuid();
            if (json.WAY_CODE.Trim().Length == 0) throw new Exception("请选择方式.");
            consumeInfo.WAY_CODE = json.WAY_CODE.Trim();
            if (!DateTime.TryParse(json.REGISTER_DATE, out tmpDt)) throw new Exception("请选择登记日期.");
            consumeInfo.REGISTER_DATE = tmpDt;
            if (!json.PRODUCT_KEY.IsGuidB()) throw new Exception("请选择配件/耗材.");
            consumeInfo.PRODUCT_KEY = json.PRODUCT_KEY.ToGuid();
            if (int.TryParse(json.ADD_POINT, out tmpInt))
            {
                if (tmpInt < 0) throw new Exception("增加积分应大于0.");
                consumeInfo.ADD_POINT = tmpInt;
            }

            if (decimal.TryParse(json.ADD_POINT, out tmpDeci)) consumeInfo.MONEY = tmpDeci;
            else throw new Exception("请输入实收金额.");
            consumeInfo.MEMO = json.MEMO;
            consumeInfo.PRODUCT_KEY = json.PRODUCT_KEY.ToGuid();
            return consumeInfo;
        }
        #endregion

        #region ClientObj

        /// <summary>
        /// Client sales consume info json obj type
        /// </summary>
        public class ConsumeJson
        {
            public string CONSUME_KEY;
            public string PRODUCT_KEY;
            public string CUSTOMER_KEY;
            public string WAY_CODE;
            public string REGISTER_DATE;
            public string MONEY;
            public string ADD_POINT;
            public string MEMO;
        }

        public class SearchOptions
        {
            public string REGISTER_DATESTART;
            public string REGISTER_DATEEND;
            public string STATE;
            public string SHOP_CODE;
            public string filterBy;
            public string filterOperater;
            public string fiterText;
        }
        #endregion

        #region Log
        private static string modeCode = "002002001";
        /// <summary>
        /// 添加配件更换维修部分日志
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <param name="logType"></param>
        private void AppendLog(CUSTOMERinfo customer, SALES_CONSUMEinfo from, SALES_CONSUMEinfo to, LogType logType)
        {
            if (null == customer) return;
            if (logType == LogType.Add)
            {
                bllSYS_LOG.SaveLog(modeCode,
                    "SALES_CONSUME",
                    from.CUSTOMER_KEY.ToString(),
                    string.Format("添加配件/耗材更换维修记录，顾客姓名:\"{0}\"  手机号:\"{1}\"", customer.NAME, customer.MOBILE),
                    "添加",
                    BusinessBase.ClientIp);
                return;
            }
            if (logType == LogType.Edit)
            {
                builder.Clear();
                builder.AppendFormat("修改配件/耗材更换维修记录，顾客姓名：\"{0}\"  手机号：\"{1}\"", customer.NAME, customer.MOBILE);
                var bChange = false;
                if (from.PRODUCT_KEY != to.PRODUCT_KEY)
                {
                    var prodMgr = new bllPRODUCT();
                    var prodF = prodMgr.GetModel(from.PRODUCT_KEY);
                    var prodT = prodMgr.GetModel(to.PRODUCT_KEY);
                    builder.AppendFormat("配件名称原值:\"{0}\"，现值:\"{1}\"", (prodF != null ? prodF.NAME : ""), (prodT != null ? prodT.NAME : ""));
                    bChange = true;
                }
                if (from.MONEY != to.MONEY)
                {
                    builder.AppendFormat("实收金额原值:\"{0}\"，现值:\"{1}\"", from.MONEY, to.MONEY);
                    bChange = true;
                }
                if (from.ADD_POINT != to.ADD_POINT)
                {
                    builder.AppendFormat("增加积分原值:\"{0}\"，现值:\"{1}\"", from.ADD_POINT.ToStringNoValue(), to.ADD_POINT.ToStringNoValue());
                    bChange = true;
                }
                if (from.WAY_CODE != to.WAY_CODE)
                {
                    builder.AppendFormat("方式原值:\"{0}\"，现值:\"{1}\"", GetWayName(from.WAY_CODE), GetWayName(to.WAY_CODE));
                    bChange = true;
                }
                if (bChange)
                {
                    bllSYS_LOG.SaveLog(modeCode,
                      "SALES_CONSUME",
                      from.CONSUME_KEY.ToString(),
                      builder.ToString(),
                      "修改",
                      BusinessBase.ClientIp);
                }
                return;
            }
            if (logType == LogType.Delete)
            {
                bllSYS_LOG.SaveLog(modeCode,
                      "SALES_CONSUME",
                      from.CONSUME_KEY.ToString(),
                      string.Format("删除配件/耗材更换维修记录，顾客姓名:\"{0}\"  手机号:\"{1}\"", customer.NAME, customer.MOBILE),
                      "删除",
                      BusinessBase.ClientIp);
            }/**/
        }
        private string GetWayName(string wayCode)
        {
            if (wayCode == "0") return "购买";
            return wayCode == "1" ? "更换" : "维修";
        }

        #endregion
    }
}
